package com.thinvent.foxit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.thinvent.foxit.entity.UserAuth;
import com.thinvent.foxit.service.UserAuthService;
import com.thinvent.foxit.util.BeanToMapConverterUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * (UserAuth)表控制层
 *
 * @author makejava
 * @since 2024-07-17 14:42:22
 */
@RestController
@RequestMapping("userAuth")
public class UserAuthController extends ApiController {
    /**
     * 服务对象
     */
    @Resource
    private UserAuthService userAuthService;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param userAuth 查询实体
     * @return 所有数据
     */
    @GetMapping("/selectAll")
    public R selectAll(Page<UserAuth> page, UserAuth userAuth, HttpServletRequest request) {
        Page<UserAuth> userAuthPage = this.userAuthService.page(page, new QueryWrapper<>(userAuth));
        // 计算占用时间
        List<UserAuth> records = userAuthPage.getRecords();
        if(CollectionUtils.isNotEmpty(records)) {
            // 获取当前时间
            Date currentTime = new Date();

            for (UserAuth record : records) {
                if(record.getOccupyStartTime() != null) {
                    // 计算占用开始时间到当前时间的差值（以毫秒为单位）
                    long diffInMilliseconds = currentTime.getTime() - record.getOccupyStartTime().getTime();

                    // 将差值转换为秒
                    int durationInSeconds = (int) TimeUnit.MILLISECONDS.toSeconds(diffInMilliseconds);

                    // 将计算出的秒数赋值给duration字段
                    record.setDuration(durationInSeconds);
                }
                if(record != null && StringUtils.isNotBlank(record.getRemoteIp())) {
                    boolean equals = record.getRemoteIp().equals(getClientIP(request));
                    if(!equals) {
                        record.setAuthStr("********");
                    }
                }
                if(record != null && StringUtils.isBlank(record.getRemoteIp())) {
                    record.setAuthStr("********");
                }
            }
        }
        // 序列化对象为JSON字符串，同时启用美化输出特性
//        String jsonString = JSON.toJSONString(userAuthPage);
//        Map<String,Object> map = JSONUtil.toBean(jsonString, Map.class);
        Map<String, Object> map = BeanToMapConverterUtil.convertToMap(userAuthPage);
        String clientIP = getClientIP(request);
        QueryWrapper<UserAuth> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("remote_ip", clientIP);
        UserAuth one = this.userAuthService.getOne(queryWrapper);
        if(one != null) {
            map.put("isbind", StringUtils.isNotEmpty(one.getRemoteIp()));
        } else {
            map.put("isbind", false);
        }
        QueryWrapper<UserAuth> wrapper = new QueryWrapper<>();
        wrapper.isNotNull("remote_ip");
        int count = this.userAuthService.count(wrapper);
        map.put("isshowpwd", count);
        return success(map);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R selectOne(@PathVariable Serializable id) {
        return success(this.userAuthService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param userAuth 实体对象
     * @return 新增结果
     */
    @PostMapping("/insert")
    public R insert(@RequestBody UserAuth userAuth) {
        return success(this.userAuthService.save(userAuth));
    }

    /**
     * 修改数据
     *
     * @param userAuth 实体对象
     * @return 修改结果
     */
    @PostMapping("/update")
    public R update(@RequestBody UserAuth userAuth) {
        return success(this.userAuthService.updateById(userAuth));
    }

    /**
     * 删除数据
     *
     * @param id 主键结合
     * @return 删除结果
     */
    @PostMapping("/delete")
    public R delete(@RequestParam("id") String id) {
        return success(this.userAuthService.removeById(id));
    }

    /**
     * 申请用户key
     * @param id
     * @return
     */
    @PostMapping("/applyUserKey")
    public R applyUserKey(@RequestParam("id") String id, @RequestParam("clientIP") String clientIP, HttpServletRequest request) {
//        String clientIP = getClientIP(request);
        return success(this.userAuthService.applyUserKey(id, clientIP));
    }

    private String getClientIP(HttpServletRequest request) {
        String clientIp = request.getHeader("X-Forwarded-For");

        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("Proxy-Client-IP");
        }
        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("WL-Proxy-Client-IP");
        }
        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("HTTP_X_FORWARDED");
        }
        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("X-Real-IP");
        }
        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getRemoteAddr();
        }

        // 如果X-Forwarded-For存在，并且不是直接来自代理（可能包含逗号分隔的IP地址），取第一个IP为客户端IP
        if (clientIp != null && !clientIp.isEmpty() && clientIp.contains(",")) {
            clientIp = clientIp.split(",")[0];
        }
        return clientIp;
    }

    /**
     * 取消申请用户key
     * @param id
     * @return
     */
    @PostMapping("/unApplyUserKey")
    public R unApplyUserKey(@RequestParam("id") String id) {
        return success(this.userAuthService.unApplyUserKey(id));
    }

    /**
     * 申请用户key(随机申请)
     * @return
     */
    @PostMapping("/applyUserKeyRandom")
    public R applyUserKeyRandom(@RequestParam("clientIP") String clientIP, HttpServletRequest request) {
//        String clientIP = getClientIP(request);
        return success(this.userAuthService.applyUserKeyRandom(clientIP));
    }

    /**
     * 申请用户key详情
     * @return
     */
    @PostMapping("/applyUserKeyDetail")
    public R applyUserKeyDetail(@RequestParam("clientIP") String clientIP, HttpServletRequest request) {
//        String clientIP = getClientIP(request);
        return success(this.userAuthService.applyUserKeyDetail(clientIP));
    }

    // 获取用户ip
    @PostMapping("/getClientIP")
    public R getClientIPV2(HttpServletRequest request) {
        return success(getClientIP(request));
    }

}

